﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CameraControl : MonoBehaviour
{
    Camera cam;
    bool ondrag;
    Vector3 worldBeginDragPos;
    Vector3 camBeginDragPos;
    GraphicRaycaster caster;

    void Start()
    {
        cam = GetComponent<Camera>();
        caster = GameObject.Find("Canvas").GetComponent<GraphicRaycaster>();
    }

    void Update()
    {
        //滚轮缩放
        float mouseScrollValue = Input.GetAxis("Mouse ScrollWheel");
        cam.orthographicSize -= mouseScrollValue;
        cam.orthographicSize = Mathf.Clamp(cam.orthographicSize, 0.1f, 100);

        if (!Utils.IsOnUI(caster, Input.mousePosition))
        {
            //拖拽
            if (Input.GetMouseButtonDown(0))
            {
                ondrag = true;
                worldBeginDragPos = cam.ScreenToWorldPoint(Input.mousePosition);
                camBeginDragPos = transform.position;
            }
            else if (Input.GetMouseButtonUp(0))
            {
                ondrag = false;
            }

            if (Input.GetMouseButton(0) && ondrag)
            {
                Vector3 currentWorldPos = cam.ScreenToWorldPoint(Input.mousePosition);
                Vector3 offset = currentWorldPos - worldBeginDragPos;
                transform.position = transform.position - offset;
            }
        }
    }
}
